import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User:龙宝
 * Date:2022-12-17
 * Time:15:38
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、从请求中获取到用户名和密码
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        if (username == null || username.equals("") || password == null || password.equals("")) {

            //用户名密码为空，直接返回登录失败
            resp.setContentType("text/html;charset=utf8");
            resp.getWriter().write("用户名或密码为空，登录失败！");
            return;
        }

        //2、查询数据库，验证用户名密码啊是否正确
        UserDao userDao = new UserDao();
        User user = userDao.selectByName(username);
        if(user == null || !user.getPassword().equals(password)) {
            //用户不存在,或密码不相同---登录失败
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("用户名或密码错误，登录失败！");
            return;

        }
        //3、如果正确，创建一个回话对象
        HttpSession session = req.getSession(true);
        //在会话中保存一下user，以备后面使用，后续访问其它页面，就可以直接通过回话拿到当前是哪个用户页面
        session.setAttribute("user",user);

        //4、构造302响应报文
        resp.sendRedirect("blog_list.html");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //针对当前登录状态进行判定
        HttpSession session = req.getSession(false);
        if(session == null) {
            //没有回话，未登录
            resp.setStatus(403);
            return;
        }
        //会存在session存在，而user不存在的情况
        User user = (User) session.getAttribute("user");
        //有会话，但没有user对象
        if(user == null) {
            resp.setStatus(403);
            return;
        }
        //默认也是200
        resp.setStatus(200);
    }
}
